package com.codeworker.app.data.repository;

import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.LiveData;

import com.codeworker.app.data.AccountRoomDatabase;
import com.codeworker.app.data.common.Constant;
import com.codeworker.app.data.dao.PropertyDao;
import com.codeworker.app.data.entity.Property;

import java.util.List;

public class PropertyRepository {
    private final PropertyDao propertyDao;
    private final LiveData<List<Property>> propertyList;

    @RequiresApi(api = Build.VERSION_CODES.N)
    public PropertyRepository(Context context) {
        AccountRoomDatabase db = AccountRoomDatabase.getDatabase(context);
        propertyDao = db.propertyDao();
        propertyList = propertyDao.getPropertyListLiveData();
    }

    public List<Property> getProperties() {
        return propertyDao.getPropertyList();
    }

    public LiveData<List<Property>> getPropertyList() {
        return propertyList;
    }

    public Property getPropertyById(int id) {
        return propertyDao.getPropertyById(id);
    }

    public void insert(Property property) {
        AccountRoomDatabase.databaseWriteExecutor.execute(() -> propertyDao.insert(property));
    }

    public void update(Property property) {
        AccountRoomDatabase.databaseWriteExecutor.execute(() -> propertyDao.update(property));
    }

    public void softDelete(Integer id) {
        Property property = propertyDao.getPropertyById(id);
        property.setIsDeleted(Constant.HAS_DELETED);
        AccountRoomDatabase.databaseWriteExecutor.execute(() -> propertyDao.update(property));
    }

    public void repay(Integer inId, Integer outId, Integer value){
        Property inProperty = propertyDao.getPropertyById(inId);
        Property outProperty = propertyDao.getPropertyById(outId);
        AccountRoomDatabase.databaseWriteExecutor.execute(() -> {
            inProperty.setValue(inProperty.getValue() + value);
            outProperty.setValue(outProperty.getValue() - value);
            propertyDao.update(inProperty);
            propertyDao.update(outProperty);
        });
    }

}
